<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/12/3
 * Time: 16:22
 */

namespace app\common\mysic\WxError;


use app\common\model\Wxapp as WxappModel;
use app\common\mysic\WxRefundErrorResponseHandle;

class LowRefundFee extends WxRefundErrorResponseHandle implements WxResponseErrorHandlerInterface
{
    public function handle()
    {
        $realBalance = $this->getRealBalance();
        if(!$realBalance) {
            return false;
        }
        $this->receivesEntity->balance = bcdiv(strval($realBalance), '100', 2);
        $this->log->info($this->receivesEntity->balance);
        return $this->receivesEntity->isUpdate(true)->save();
    }

    public function getRealBalance()
    {
        $page = 1;
        $refundAmount = 0;
        $wxConfig = WxappModel::getWxappCache($this->refundOrderEntity->wxapp_id);
        $this->wxApi->setConfigArr($wxConfig);

        try {
            $this->log->info('开始', '微信退款查询');
            $ret = $this->wxApi->refundQuery($this->refundOrderEntity->transaction_id, $this->refundOrderEntity->pay_price, $this->bonus, $page);
        } catch(\Throwable $t) {
            $this->log->error(exceptionLogFormat($t), '微信退款查询异常');
            return false;
        }
        if(!$ret){
            return false;
        }
        $response = $this->wxApi->getResponse();
        $this->log->info($response, '微信退款查询结果');
        $totalRefundCount = $response['total_refund_count'];
        $totalFee = $response['total_fee'];
        $refundAmount += $response['refund_fee'];
        $totalPage = intval(ceil($totalRefundCount / 10)) - 1;
        if($totalPage) {
            while($totalPage > 0) {
                $page++;
                $this->wxApi->refundQuery($this->refundOrderEntity->transaction_id, $this->refundOrderEntity->pay_price, $this->bonus, $page);
                $response = $this->wxApi->getResponse();
                $refundAmount += $response['refund_fee'];
                $totalPage--;
            }
        }
        return $totalFee - $refundAmount;
    }
}